import 'dart:async';
import 'package:flutter/material.dart';
import 'package:razer_one/app/main/model/eventbus_model.dart';
import 'package:razer_one/app/main/utils/app_manager.dart';

class MainSlideCell extends StatefulWidget {
  final Widget child;
  final List<Widget> buttons;
  final double singleButtonWidth;
  final int index; //用来标记是第几个cell
  final VoidCallback? onSlideStarted;
  final VoidCallback? onSlideCompleted;
  final VoidCallback? onSlideCanceled;
  const MainSlideCell(
      {Key? key,
      required this.child,
      required this.buttons,
      required this.singleButtonWidth,
      required this.index,
      this.onSlideStarted,
      this.onSlideCompleted,
      this.onSlideCanceled})
      : super(key: key);

  @override
  State<MainSlideCell> createState() => _MainSlideCellState();
}

class _MainSlideCellState extends State<MainSlideCell>
    with TickerProviderStateMixin {
  double translateX = 0;
  double maxDragDistance = 0;

  late AnimationController animationController;
  StreamSubscription? stream;
  @override
  void initState() {
    super.initState();
    maxDragDistance = widget.singleButtonWidth * widget.buttons.length;

    animationController = AnimationController(
        lowerBound: -maxDragDistance,
        upperBound: 0,
        vsync: this,
        duration: const Duration(milliseconds: 150))
      ..addListener(() {
        translateX = animationController.value;

        setState(() {});
      });

    //监听信号
    stream = //监听信号,我要买,我要卖
        AppManager.instance.eventBus?.on<SlideCellModel>().listen((model) {
      int index = model.index;
      if (index < 0 || index != widget.index) {
        close();
      }
    });
  }

  @override
  void dispose() {
    animationController.dispose();
    stream?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        child: Stack(
          children: <Widget>[
            Positioned.fill(
                child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: widget.buttons,
            )),
            GestureDetector(
              onHorizontalDragDown: onHorizontalDragDown,
              onHorizontalDragUpdate: onHorizontalDragUpdate,
              onHorizontalDragEnd: onHorizontalDragEnd,
              child: Transform.translate(
                offset: Offset(translateX, 0),
                child: Row(
                  children: <Widget>[
                    Expanded(
                      flex: 1,
                      child: widget.child,
                    )
                  ],
                ),
              ),
            ),
          ],
        ),
        onWillPop: () async {
          if (translateX != 0) {
            close();
            return false;
          }
          return true;
        });
  }

  void onHorizontalDragDown(DragDownDetails details) {
    if (widget.onSlideStarted != null) {
      widget.onSlideStarted!();
    }

    close();
  }

  void onHorizontalDragUpdate(DragUpdateDetails details) {
    translateX = (translateX + details.delta.dx).clamp(-maxDragDistance, 0.0);
    setState(() {});
  }

  void onHorizontalDragEnd(DragEndDetails details) {
    animationController.value = translateX;
    if (details.velocity.pixelsPerSecond.dx > 200) {
      close();
    } else if (details.velocity.pixelsPerSecond.dx < -200) {
      open();
    } else {
      if (translateX.abs() > 15) {
        open();
      } else {
        close();
      }
    }
  }

  void open() {
    if (translateX != -maxDragDistance) {
      animationController.animateTo(-maxDragDistance);
    }
  }

  void close() {
    if (translateX != 0) {
      animationController.animateTo(0);
    }
  }
}
